package com.fulihui.wgj.biz.impl;

import com.fulihui.common.constants.WxRegionLevelConstants;
import com.fulihui.common.conv.BeanConv;
import com.fulihui.common.enums.ContainOrEliminateEnum;
import com.fulihui.wgj.biz.WxRegionBiz;
import com.fulihui.wgj.dal.mybatis.domain.WxRegion;
import com.fulihui.wgj.dal.mybatis.repository.WxRegionRepository;
import com.fulihui.wgj.facade.dto.WxRegionDTO;
import com.fulihui.wgj.facade.request.region.WxRegionQueryProvinceRequest;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wang_wx
 * @date 2018-06-28
 */
@Component
public class WxRegionBizImpl implements WxRegionBiz {

    private static final Logger LOGGER = LoggerFactory.getLogger(WxRegionBizImpl.class);

    @Autowired
    WxRegionRepository wxRegionRepository;

    @Override
    public Map<String, String> getAllRegionMap() {

        HashMap<String, String> resultMap = Maps.newHashMap();

        Stopwatch stopwatch = Stopwatch.createStarted();

        LOGGER.info("查询地理区域信息start");

        // 查询所有国家-1级
        WxRegion regionCountry = new WxRegion();
        regionCountry.setLevel(WxRegionLevelConstants.LEVEL_COUNTRY);
        List<WxRegion> regionsCountrys = wxRegionRepository.queryByWhere(regionCountry);
        fillMap(regionsCountrys, resultMap);

        // 查询所有省份-2级
        List<WxRegion> regionsProvinces = wxRegionRepository.queryRegionForLevelProvice();
        fillMap(regionsProvinces, resultMap);

        // 查询所有城市-3级
        List<WxRegion> regionsCitys = wxRegionRepository.queryRegionForLevelCity();
        fillMap(regionsCitys, resultMap);

        long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        LOGGER.debug("查询地理区域信息end,查询耗时[{}]毫秒", elapsed);
        return resultMap;
    }

    @Override
    public List<WxRegionDTO> queryAllCountry() {
        List<WxRegionDTO> dtoList = null;
        List<WxRegion> wxRegionList;
        wxRegionList = wxRegionRepository.queryWxRegionByLevel(WxRegionLevelConstants.LEVEL_COUNTRY);
        if (!CollectionUtils.isEmpty(wxRegionList)) {
            dtoList = BeanConv.copy(wxRegionList, WxRegionDTO.class);
            topChina(dtoList, null);
        }
        return dtoList;
    }

    @Override
    public List<WxRegionDTO> queryProvince(WxRegionQueryProvinceRequest request) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        List<String> countryIds = request.getCountryIds();
        String countryTab = request.getCountryTab();
        List<WxRegionDTO> list = Lists.newArrayList();
        List<WxRegion> wxRegions = null;
        if (!CollectionUtils.isEmpty(countryIds)) {
            if (StringUtils.equals(countryTab, ContainOrEliminateEnum.CONTAIN.getCode())) {
                //直接查出国家下面所有的城市
                wxRegions = wxRegionRepository.queryProvinceByPids(countryIds);
            } else {
                wxRegions = wxRegionRepository.queryProvinceNotInPids(countryIds);
            }
        }
        if (!CollectionUtils.isEmpty(wxRegions)) {
            list = BeanConv.copy(wxRegions, WxRegionDTO.class);
        }
        long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        LOGGER.debug("查询省份耗时[{}]毫秒", elapsed);
        return list;
    }

    /**
     * 填充map
     *
     * @param regions
     * @param resultMap
     */
    private void fillMap(List<WxRegion> regions, HashMap<String, String> resultMap) {
        if (!CollectionUtils.isEmpty(regions)) {
            regions.forEach(wxRegion -> resultMap.put(wxRegion.getName(), wxRegion.getRid()));
        }
    }

    /**
     * 置顶中国
     *
     * @param dtoList
     * @param pid
     */
    private void topChina(List<WxRegionDTO> dtoList, String pid) {
        if (StringUtils.isEmpty(pid)) {
            int index = -1;
            WxRegionDTO chinaDTO = null;
            for (int i = 0; i < dtoList.size(); i++) {
                WxRegionDTO wxRegionDTO = dtoList.get(i);
                if (wxRegionDTO.getName().equals("中国")) {
                    index = i;
                    chinaDTO = wxRegionDTO;
                    break;
                }
            }
            if (index != -1) {
                dtoList.remove(index);
                dtoList.add(0, chinaDTO);
            }
        }
    }

}
